//
// Created by HP on 2024/2/21.
//

#include "nrf24l01_driver.h"



NRF24L01_Driver::NRF24L01_Driver(SPI_HandleTypeDef *spi,GPIO_TypeDef* CS_Port,uint16_t CS_Pin,GPIO_TypeDef* CE_Port,uint16_t CE_Pin){
    _hspi = spi;
    _CS_Port = CS_Port;
    _CS_Pin  = CS_Pin;
    _CE_Port = CE_Port;
    _CE_Pin  = CE_Pin;

    _CE_Low();
    _CS_High();
    HAL_Delay(10);
}

void NRF24L01_Driver::_CS_High(){
    HAL_GPIO_WritePin(_CS_Port,_CS_Pin,GPIO_PIN_SET);
}
void NRF24L01_Driver::_CS_Low(){
    HAL_GPIO_WritePin(_CS_Port,_CS_Pin,GPIO_PIN_RESET);
}
void NRF24L01_Driver::_CE_High(){
    HAL_GPIO_WritePin(_CE_Port,_CE_Pin,GPIO_PIN_SET);
}
void NRF24L01_Driver::_CE_Low(){
    HAL_GPIO_WritePin(_CE_Port,_CE_Pin,GPIO_PIN_RESET);
}
void NRF24L01_Driver::_spi_mode_set(){
    //    if(hspi->Init.CLKPhase == SPI_PHASE_2EDGE){
//        return;
//    };

    if (HAL_SPI_DeInit(_hspi) != HAL_OK)
    {
        while( true )
            usb_printf("as5047p spi deinit error\r\n");
    }

    _hspi->Instance = _hspi->Instance;
    _hspi->Init.Mode = SPI_MODE_MASTER;
    _hspi->Init.Direction = SPI_DIRECTION_2LINES;
    _hspi->Init.DataSize = SPI_DATASIZE_8BIT;
    _hspi->Init.CLKPolarity = SPI_POLARITY_LOW;
    _hspi->Init.CLKPhase = SPI_PHASE_1EDGE;
    _hspi->Init.NSS = SPI_NSS_SOFT;
    _hspi->Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_64;
    _hspi->Init.FirstBit = SPI_FIRSTBIT_MSB;
    _hspi->Init.TIMode = SPI_TIMODE_DISABLE;
    _hspi->Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
    _hspi->Init.CRCPolynomial = 10;
    if (HAL_SPI_Init(_hspi) != HAL_OK)
    {
        while( true )
            usb_printf("as5047p spi deinit error\r\n");
    }
}


void NRF24L01_Driver::read(uint8_t reg ,uint8_t *data,uint8_t len){
    _spi_mode_set();
    _CS_Low();
    HAL_SPI_Transmit(_hspi,&reg,1,0xffff);
    HAL_SPI_Receive(_hspi,data,len,0xffff);
    _CS_High();

}
void NRF24L01_Driver::write(uint8_t reg,uint8_t *data,uint8_t len){
    _spi_mode_set();
    _CS_Low();
    HAL_SPI_Transmit(_hspi,&reg,1,0xffff);
    HAL_SPI_Transmit(_hspi,data,len,0xffff);
    _CS_High();
}
